package com.itqf.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/21
 * @Time: 下午2:41
 */
@Controller
public class FileController {


    @RequestMapping("/doUpload")
    @ResponseBody
    /**
     *   <input type="file" name="photo">
     *     <br>
     *     <input type="text" name="name">
     */
    public Map<String,Object>  doUpload(MultipartFile photo, String name, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        try {
            //1,得到文件名  djsidjsiods.jpg
            String filename = photo.getOriginalFilename();
            //2.指定文件存储路径
            String path =  request.getServletContext().getRealPath("/upload");
            File dir = new File(path);
            if (!dir.exists()){
                dir.mkdir();
            }
            //3.文件的后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            //4.新文件名称
            filename = UUID.randomUUID().toString().replace("-","")+suffix;

            //5.io
            photo.transferTo(new File(dir,filename));
            map.put("code",0);
            map.put("msg","上传成功");

            return  map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("code",1);
        map.put("msg","上传失败");
        return  map;

    }

    @RequestMapping("/downloadFile")
    public  void  downloadFile(String name,HttpServletRequest request,HttpServletResponse response){

        try {
            //1.文件路径
            String  filepath = request.getServletContext().getRealPath("/upload");
            //2.文件名 e157ee81210a4a68a13a1dcd9243a02a.gif

            //3.响应头
            response.setHeader("content-disposition","attachment;filename="+name);

            //4.把文件响应客户端
            IOUtils.copy(new FileInputStream(new File(filepath,name)),response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
